package com.lzy.cloud.sms.config;

import com.lzy.cloud.sms.constant.RedisPrefix;
import com.lzy.cloud.sms.dtos.SmsConfigDto;
import com.lzy.cloud.sms.dtos.SmsTemplateDto;
import com.lzy.cloud.sms.service.SmsConfigService;
import com.lzy.cloud.sms.service.SmsTemplateService;
import com.lzy.framework.core.cache.cluster.RedisClusterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.TreeSet;

@Configuration
@Slf4j
public class SmsConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private RestTemplateBuilder builder;

    @Autowired
    private SmsTemplateService smsTemplateService;

    @Autowired
    private RedisClusterService redisClusterService;

    @Autowired
    private SmsConfigService smsConfigService;

    @Bean
    public RestTemplate restTemplateGenerator() {
        return builder.build();
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        initSmsTemplate();
        initSmsConfig();
    }

    /**
     * 向redis初始化短信模板
     */
    private void initSmsTemplate() {
        log.info("----初始化短信模板数据start----");
        List<SmsTemplateDto> smsTemplateDtoList = smsTemplateService.query(null, null);
        log.info("同步数据条数--->" + smsTemplateDtoList.size());
        TreeSet<String> keys = redisClusterService.keys(RedisPrefix.SmsTemplate + "*");
        for (String k : keys) {
            redisClusterService.del(k);
        }
        for (SmsTemplateDto smsTemplateDto : smsTemplateDtoList) {
            redisClusterService.setObject(RedisPrefix.SmsTemplate + smsTemplateDto.getBusiType(), smsTemplateDto);
        }
        log.info("----初始化短信模板数据end----");
    }

    /**
     * 向redis初始化短信配置
     */
    private void initSmsConfig() {
        log.info("----初始化短信配置数据start----");
        List<SmsConfigDto> smsConfigDtoList = smsConfigService.allVailable();
        log.info("同步数据条数--->" + smsConfigDtoList.size());
        TreeSet<String> keys = redisClusterService.keys(RedisPrefix.SmsConfig + "*");
        for (String k : keys) {
            redisClusterService.del(k);
        }
        for (SmsConfigDto smsConfigDto : smsConfigDtoList) {
            redisClusterService.setObject(RedisPrefix.SmsConfig + smsConfigDto.getId(), smsConfigDto);
        }
        log.info("----初始化短信配置数据end----");
    }

}
